const { sequelize } = require('../utils/sequelize');
const { v4: uuidv4 } = require('uuid');

class ClassTimeService {
    constructor() {
    }

    async findAll(){
        let data = null;
        try {
            data = await sequelize.models.ClassTime.findAll();
        } catch (error) {
            error['name'] = error.name || '未知错误'
            console.log(error)
            return error;
        }
        return data;
    }

    async findById(classTimeId){
        let data = null;
        try {
            data = await sequelize.models.ClassTime.findOne({
                where: {id: classTimeId}});
        } catch (error) {
            error['name'] = error.name || '未知错误'
            console.log(error)
            return error;
        }
        
        return data;
    }

    async saveClassTime(classTimeObj){
        let data = null;
        try {
            classTimeObj['id'] = uuidv4();
            data = await sequelize.models.ClassTime.create(classTimeObj)
        } catch (error) {
            error['name'] = error.name || '未知错误'
            console.log(error)
            return error;
        }
        return data;
    }

    async deleteClassTime(classTimeId){
        let data = null;
        try {
            let hasUse = await sequelize.models.Course.findOne({
                where: {
                    classTimeId: classTimeId
                }
            })
            if(hasUse) return { name: '还存在课程使用该上课时间，不能删除'}
            
            data = await sequelize.models.ClassTime.destroy({
                where: {id: classTimeId}});
        } catch (error) {
            console.log(error);
            error['name'] = error.name || '未知错误'
            return error;
        }
        return data;
    }
}

module.exports = new ClassTimeService();